<?php


namespace common\service;


use common\annotation\AuthCode;
use ReflectionMethod;
use Webman\Http\Request;

class AuthService
{
    static function checkAuth(Request $request, $authority, ReflectionMethod $method)
    {
        // 访问的方法需要鉴权
        $attributes = $method->getAttributes(AuthCode::class);
        $flag = true;
        if ($attributes) {
            //判断如果满足注解鉴权,优先进行注解鉴权
            if ($ins = $attributes[0]->newInstance()) {
                $flag = self::annotationRight($ins->code, $ins->op, $authority);
            }
        } else {
            //按照路由$request->path()鉴权
            $flag = self::routerPathRight($request, $authority);
        }
        return $flag;

    }

    private static function routerPathRight(Request $request, $authority)
    {
        $code1 = $request->path();
        $code2 = str_replace("/", ':', $request->path());
        //只需要一个
        foreach ([$code1, $code2] as $value) {
            if (in_array($value, $authority)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 注解鉴权
     * 兼容权限与访问路径不一致的时候使用system:user:search 鉴权 system/user/list
     * 或者单接口多权限时使用
     * @param $code
     * @param $op
     * @param $authority
     * @return bool
     */
    private static function annotationRight($code, $op, $authority)
    {
        if ($op == 'AND') {
            //全部权限要有
            $flag = true;
            foreach ($code as $value) {
                if (!in_array($value, $authority)) {
                    $flag = false;
                }
            }
            return $flag;
        } else {
            //只需要一个
            foreach ($code as $value) {
                if (in_array($value, $authority)) {
                    return true;
                }
            }
        }
        return true;
    }
}